<template>
  <div>
    <AModal
      v-bind="$attrs"
      width="800px"
      @close="modalEvent('close')"
      @ok="modalEvent('ok')"
      @open="modalEvent('open')"
      @cancel="modalEvent('cancel')"
    >
      <AForm ref="formRef" :model="form" auto-label-width>
        <ARow :gutter="10">
          <ACol v-if="form.purchaseOrderCode" :span="12">
            <AFormItem field="name" label="采购单号">
              {{ form.purchaseOrderCode }}
            </AFormItem>
          </ACol>
          <ACol :span="12">
            <AFormItem
              field="supplierId"
              label="供应商"
              :rules="[{ required: true, message: '请选择供应商' }]"
              :validate-trigger="['change', 'blur']"
            >
              <ASelect v-model="form.supplierId" allow-search placeholder="请选择供应商">
                <AOption
                  v-for="(item, index) in supplierList"
                  :key="index"
                  :label="item.supplierName"
                  :value="item.supplierId"
                ></AOption>
              </ASelect>
            </AFormItem>
          </ACol>
          <ACol :span="12">
            <AFormItem field="isInclTax" label="含税">
              <ASelect v-model="form.isInclTax" placeholder="是否含税" allow-search>
                <AOption label="是" :value="1"></AOption>
                <AOption label="否" :value="0"></AOption>
              </ASelect>
            </AFormItem>
          </ACol>
          <ACol :span="12">
            <AFormItem field="deliveryDate" label="交货日期">
              <ADatePicker
                v-model="form.deliveryDate"
                placeholder="交货日期"
                class="w100"
              ></ADatePicker>
            </AFormItem>
          </ACol>
        </ARow>
        <ACard
          v-for="(item, index) in form.detailList"
          :key="index"
          class="card-container"
          size="small"
        >
          <template #extra>
            <ALink v-if="!form.inboundStatus" @click="editProduct('add')">增加材料</ALink>
            <ALink
              v-if="!form.inboundStatus && form.detailList.length > 1"
              @click="editProduct('del', index)"
            >
              删除材料
            </ALink>
          </template>
          <ARow :gutter="10">
            <ACol :span="12">
              <AFormItem
                label="材料名称"
                :field="`detailList[${index}].productId`"
                :rules="[{ required: true, message: '请输入材料名称' }]"
                :validate-trigger="['change', 'input', 'blur']"
              >
                <ASelect
                  v-if="!form.inboundStatus"
                  v-model="item.productId"
                  v-model:input-value="productSearch"
                  allow-search
                  placeholder="材料名称"
                  :trigger-props="{ contentStyle: { width: 'max-content' } }"
                  :filter-option="proFilter"
                  @change="changeEvent('material', item)"
                >
                  <template #empty>
                    <div style="padding: 6px 12px">
                      <ALink :hoverable="false" @click="openAdd()"> 新增材料 </ALink>
                    </div>
                  </template>
                  <AOption
                    v-for="(item, index) in productList"
                    :key="index"
                    :label="item.productName"
                    :value="`${item.productId}-${item.specModel}`"
                    :disabled="detailIds.includes(`${item.productId}-${item.specModel}`)"
                  >
                    <div class="w100 erp-row-center-between">
                      <div>{{ item.productName }}</div>
                      <ATag v-if="item.specModel" color="blue">
                        {{ item.specModel }}
                      </ATag>
                    </div>
                  </AOption>
                </ASelect>
                <div v-else>{{ item.productName }}</div>
              </AFormItem>
            </ACol>
            <ACol :span="12">
              <AFormItem field="specModel" label="规格型号">
                {{ item.specModel }}
              </AFormItem>
            </ACol>
            <ACol :span="12">
              <AFormItem field="unit" label="单位">
                {{ item.unit }}
              </AFormItem>
            </ACol>
            <ACol :span="12">
              <AFormItem field="qty" label="数量">
                <AInputNumber
                  v-if="!form.inboundStatus"
                  v-model="item.qty"
                  placeholder="请输入数量"
                  :precision="2"
                  :step="1"
                  hide-button
                  model-event="input"
                  @change="inputEvent('qty', item)"
                />
                <div v-else>{{ item.qty }}</div>
              </AFormItem>
            </ACol>
            <ACol :span="12">
              <AFormItem field="unitPrice" label="单价">
                <AInputNumber
                  v-if="!form.inboundStatus"
                  v-model="item.unitPrice"
                  placeholder="请输入单价"
                  :precision="4"
                  :step="1"
                  hide-button
                  model-event="input"
                  @change="inputEvent('unitPrice', item)"
                />
                <div v-else>{{ item.unitPrice }}</div>
              </AFormItem>
            </ACol>
            <ACol :span="12">
              <AFormItem field="amt" label="计算方式">
                <div v-if="!form.inboundStatus" class="erp-column-item-start">
                  <ARadioGroup
                    v-model="item.calcPriceMethod"
                    :default-value="0"
                    @change="changeEvent('calcPriceMethod', item)"
                  >
                    <ARadio :value="0">数量</ARadio>
                    <ARadio :value="1">面积</ARadio>
                  </ARadioGroup>
                  <div v-if="item.calcPriceMethod === 1" style="font-size: 12px; color: #ff8900">
                    该计算方式按照毫米(mm)转换米(m)进行计算
                  </div>
                </div>
                <div v-else>{{ item.calcPriceMethod == 1 ? '面积' : '数量' }}</div>
              </AFormItem>
            </ACol>
            <ACol :span="12">
              <AFormItem field="amt" label="金额">
                <div>{{ `¥${formatPrice(item.amt || 0, 4)}` }}</div>
              </AFormItem>
            </ACol>
          </ARow>
        </ACard>
        <ARow :gutter="10">
          <ACol>
            <AFormItem field="remark" label="备注">
              <ATextarea v-model="form.remark" />
            </AFormItem>
          </ACol>
        </ARow>
      </AForm>
    </AModal>
    <addProduct
      v-model:visible="addProductVisible"
      title="新增其它"
      :check-data="{ productName: productSearch }"
      @reload="getProductList"
    ></addProduct>
  </div>
</template>

<script lang="ts" setup>
import { Message, SelectOptionData } from '@arco-design/web-vue'
import { getSupplierAllList, SupplierResItem } from '@renderer/api/company'
import { formatPrice } from '@renderer/utils/mixins'
import {
  editPurchase,
  getPurchaseDetail,
  PurchaseReq,
  PurchaseResItem
} from '@renderer/api/purchasingDep'
import { getProductAllList, ProductResItem } from '@renderer/api/salesDep'
import { useMenuState } from '@renderer/store'
import { getArrayItemType } from '@renderer/types/global'
import { deleteNullObject } from '@renderer/utils/data-processing'
import { decimalRound } from '@renderer/utils/mixins'
import addProduct from './addOther.vue'
import { isEmpty } from 'lodash-es'

interface Props {
  [key: string]: any
  checkData?: Partial<PurchaseResItem>
}
const props = withDefaults(defineProps<Props>(), {
  checkData: () => {
    return {}
  }
})
const emit = defineEmits(['update:visible', 'reload'])
const attrs = useAttrs()
const formRef = ref()
const detailIds = computed(() => form.value.detailList.map((item) => item.productId))
const form = ref<PurchaseReq>({
  supplierId: '',
  deliveryDate: '',
  isInclTax: 1,
  formType: 2,
  detailList: [
    {
      unitPrice: 0,
      productId: '',
      qty: 0,
      amt: 0,
      unit: '',
      specModel: '',
      calcPriceMethod: 0
    }
  ],
  inboundStatus: 0,
  remark: ''
})
const supplierList = ref<SupplierResItem[]>([])
const productList = ref<ProductResItem[]>([])
const menuParam = useMenuState()
const addProductVisible = ref(false)
const productSearch = ref('')

// 获取客户列表
const getCompanyList = () => {
  getSupplierAllList({ supplierName: '' }).then((res) => {
    supplierList.value = res.data.list
  })
}
// 获取产品列表
const getProductList = () => {
  getProductAllList({ productType: 3 }).then((res) => {
    productList.value = res.data.list
  })
}
// 获取详情
const getDetail = () => {
  getPurchaseDetail({ purchaseOrderId: props.checkData.purchaseOrderId! }).then((res) => {
    res.data.detailList.map((item) => {
      item.productId = `${item.productId}-${item.specModel}`
    })
    form.value = res.data
    if (isEmpty(form.value.detailList)) {
      form.value.detailList = [
        {
          unitPrice: 0,
          productId: '',
          qty: 0,
          amt: 0,
          unit: '',
          specModel: '',
          calcPriceMethod: 0
        }
      ]
    }
    if (attrs.title === '复制') {
      form.value.inboundStatus = 0
      form.value.purchaseOrderCode = ''
      form.value.detailList = form.value.detailList!.map((item) => {
        item.purchaseOrderDetailId = undefined
        return item
      })
    }
  })
}

// 弹窗事件
const modalEvent = (type: string) => {
  switch (type) {
    case 'ok':
      formRef.value.validate((errors: any) => {
        if (!errors) {
          // 新增
          if (['新增', '复制'].includes(attrs.title as string)) {
            form.value.purchaseOrderId = undefined
          }
          form.value.formType = 2
          form.value.detailList.map((item) => {
            item.productId = item.productId?.split('-')[0]
            return item
          })
          editPurchase(deleteNullObject(form.value)).then(() => {
            Message.success(
              ['新增', '复制'].includes(attrs.title as string) ? '新增成功' : '修改成功'
            )
            modalEvent('cancel')
            emit('reload')
          })
        }
      })
      break
    case 'close':
      menuParam.switchEditStatus(false)
      formRef.value.resetFields()
      form.value = {
        inboundStatus: 0,
        supplierId: '',
        deliveryDate: '',
        isInclTax: 1,
        formType: 2,
        detailList: [
          {
            unitPrice: 0,
            productId: '',
            qty: 0,
            amt: 0,
            unit: '',
            specModel: '',
            calcPriceMethod: 0
          }
        ],
        remark: ''
      }
      emit('update:visible', false)
      break
    case 'open':
      menuParam.switchEditStatus(true)
      getCompanyList()
      getProductList()
      if (['修改', '复制'].includes(attrs.title as string)) {
        getDetail()
      }
      break
    case 'cancel':
      menuParam.switchEditStatus(false)
      formRef.value.resetFields()
      emit('update:visible', false)
      break
    default:
      break
  }
}

const editProduct = (type: 'add' | 'del', index?: number) => {
  switch (type) {
    case 'add':
      form.value.detailList.push({
        unitPrice: 0,
        productId: '',
        qty: 0,
        amt: 0,
        unit: '',
        specModel: '',
        calcPriceMethod: 0
      })
      break
    case 'del':
      form.value.detailList.splice(index!, 1)
      break

    default:
      break
  }
}

const inputEvent = (
  type: 'qty' | 'unitPrice',
  paramsItem: getArrayItemType<PurchaseReq['detailList']>
) => {
  switch (type) {
    case 'qty':
      if (paramsItem.calcPriceMethod === 0) {
        paramsItem.amt = Number(decimalRound(paramsItem.qty! * paramsItem.unitPrice!, 4))
      } else {
        if (!paramsItem.specModel) {
          return
        }
        const sizes = paramsItem.specModel?.split('*').map(Number)
        const area = sizes[0] * sizes[1]
        paramsItem.amt = Number(
          decimalRound((paramsItem.qty! * paramsItem.unitPrice! * area) / 1000 / 1000, 4)
        )
      }
      break
    case 'unitPrice':
      if (paramsItem.calcPriceMethod === 0) {
        paramsItem.amt = Number(decimalRound(paramsItem.qty! * paramsItem.unitPrice!, 4))
      } else {
        if (!paramsItem.specModel) {
          return
        }
        const sizes = paramsItem.specModel?.split('*').map(Number)
        const area = sizes[0] * sizes[1]
        paramsItem.amt = Number(
          decimalRound((paramsItem.qty! * paramsItem.unitPrice! * area) / 1000 / 1000, 4)
        )
      }
      break
    default:
      break
  }
}

const changeEvent = (type: string, detailInfo: getArrayItemType<PurchaseReq['detailList']>) => {
  switch (type) {
    case 'material':
      {
        const temp = productList.value.find(
          (item) => `${item.productId}-${item.specModel}` === detailInfo.productId
        )
        if (temp) {
          detailInfo.spec = temp.specModel
          detailInfo.unit = temp.unit
        }
        if (detailInfo.calcPriceMethod === 1) {
          changeEvent('calcPriceMethod', detailInfo)
        }
      }
      break
    case 'calcPriceMethod':
      {
        const sizes = detailInfo.specModel?.split('*')
        const isNum = sizes?.every((item) => /^\d+$/.test(item))
        if (detailInfo.calcPriceMethod === 1) {
          if (!detailInfo.specModel?.includes('*') || !isNum) {
            Message.error('当前产品规格不允许使用面积计算方式,请修改成“215*321”格式')
            detailInfo.calcPriceMethod = 0
          }
        }
      }
      break
    default:
      break
  }
}

// 新增产品
const openAdd = () => {
  addProductVisible.value = true
}

const proFilter = (inputValue: string, option: SelectOptionData) => {
  return (
    (option.value as string)?.split('-')[1].includes(inputValue) ||
    option.label?.includes(inputValue)
  )
}
</script>
<style scoped>
.card-container {
  margin-bottom: 10px;
}

:deep(.arco-select-option-content) {
  width: 100%;
}
</style>
